/*
* Copyright (C) 2020 ~ 2024 chaigec All Rights Reserved.
*
* Author:     chaigec <chaigec@163.com>
* Maintainer: chaigec <chaigec@163.com>

 * Use of this source code is governed by MIT license that can be found in the
 * LICENSE file in the root of the source tree. All contributing project authors
 * may be found in the AUTHORS file in the root of the source tree.
*/

#ifndef MK_HTTP_CLIENT_H
#define MK_HTTP_CLIENT_H
#include "MkTcp/MkTcpClient.h"
#include "MkHttpResponse.h"
#include "MkHttpUtil.h"
#include "MkUtil/MkLock.h"
#include <atomic>

class CMkHttpClient;
typedef MkFunction<void(const MkHttpStatusCode& StatusCode, const MkString& Res)>  MkHttpResponseCb;
typedef MkFunction<void(const Uint8* pBuf, Uint32 nLen)> MkWebsocketRecvCb;
typedef MkFunction<void()> MkWebSocketCloseCb;
typedef MkFunction<void()> MkWebSocketConnectedCb;
class MkApi CMkHttpClient : public CMkTcpClient
{
public:
    CMkHttpClient(CMkEvent *pEvent, CMkTimer* pTimer, const MkEventRemovedCallback& HttpEventRemovedCb);
    virtual ~CMkHttpClient();

    Uint32 SendRequest(const MkHttpMethod& Method, const MkString& HttpUrl, const MkMapString& MapParam, const MkString& Body, const MkMapString& MapHeader, const MkHttpResponseCb& ResponseCb, Uint32 TimeMilSeconds = 5000);
    Uint32 WebSocketConnect(const MkString& Path, const MkWebSocketConnectedCb& ConnectedCb, const MkWebsocketRecvCb& RecvCb, const MkWebSocketCloseCb& CloseCb);
    Uint32 SendWebSocketMessage(const MkString& Content);
    BOOL IsFree();
    Uint32 SetNotFree();
    void SetSendPingFlag(BOOL bSendPing) { m_bSendPing = bSendPing; }
protected:
    Uint32 OnClose() override;
    Uint32 OnRecv() override;
    Uint32 OnEventRemoved() override;
    Uint32 ParseResponse(const CMkHttpResponse& pRes);
    Uint32 WebSocketRecvParse(const Uint8* pBuf, Uint32 nLen, Uint32& nUsed);
    Uint32 HttpRecvParse(const Uint8* pBuf, Uint32 nLen, Uint32& nUsed);
    Uint32 WebSocketSendPing();
    Uint32 WebSocketSendPong();
private:
    std::atomic<BOOL>                       m_bFree;
    BOOL                                    m_bWebSocket;
    BOOL                                    m_bSendPing;
    MkString                                m_WebSocketAccessKey;
    MkString                                m_WebSocketProtocol;
    MkString                                m_WsAccept;
    MkHttpResponseCb                        m_HttpResponseCb;

    MkWebsocketRecvCb                       m_WebsocketRecvCb;
    MkWebSocketCloseCb                      m_WebsocketCloseCb;
    MkWebSocketConnectedCb                  m_WebsocketConnectedCb;

    MkString                                m_RequestDelayer;
    CMkHttpResponse                         m_Response;
    MkString                                m_WebsocketMsg;

    Uint8                                   *m_pRecvBuf;
    Uint32                                  m_nLen;
    Uint32                                  m_nOffset;
};





#endif